﻿
var urllist = "/shareData/list.do";
var urlSave = "/shareData/save.do";
var urlInfo = "/shareData/content/info.do";
var urlSeach = "/shareData/seach.do";
function timestamp(url){
    //  var getTimestamp=Math.random();
    var getTimestamp=new Date().getTime();
    if(url.indexOf("?")>-1){
        url=url+"&timestamp="+getTimestamp
    }else{
        url=url+"?timestamp="+getTimestamp
    }
    return url;
}

(function () {

    var permit = true;
    var allow = true;

    var getId = new Array()

    var iWidth = document.documentElement.offsetWidth;//获取屏幕宽度-------------------------------------------
    var iHeight = document.documentElement.offsetHeight;//获取屏幕高度----------------------------
    var dateTime;

    $(function () {

        $_dataGrid()

    })



    function $_dataGrid(pageSize,pageNum) {

        var dataList;
        var start;

        if(!pageSize&&!pageNum){
            dataList = {
                page:1,
                pageSize:20,
            }
            start = 0;
        }else {
            dataList = {
                page:pageNum,
                pageSize:pageSize,
            }
            start = (pageNum-1) * pageSize;
        }

        $.get(urllist,dataList,function (json) {
            var result = eval('(' + json + ')');
            var data = result["data"]['results'];
            var total = result["data"]['size'];
            var endLength = total%pageSize;
            var eLength;
            if(pageNum == Math.ceil(total/pageSize)){
                if(endLength!==0){
                    eLength = endLength;
                }
                else{
                    eLength = dataList.pageSize;
                }
            }
            else {
                eLength = dataList.pageSize;

            }
            $("#shareData").datagrid({
                title:"管理",
                fitColumns: true,
                showFooter: true,
                singleSelect:true,
                fit: true,
                width:iWidth,
                height:iHeight,
                striped:true,
                pagination:true,
                rownumbers:true,
                columns:[$_columns()],
                data:data,
                onClickRow:function (index,row) {
                    if(permit) {
                        if(row.type>3){
                            $.messager.alert('确认','仅支持excel,word,pdf预览');
                            return
                        }
                        getId.push(row.cid)
                        $_preview(row.cid,row.title)
                    }
                },
                onClickCell:function (index, field, value) {

                    if(field !="format"){
                        permit = true;
                    }
                },

                toolbar:[{text:'上传',
                    iconCls:'icon-add',
                    width:100,
                    handler:function () {
                        $_uploadView()
                    }
                },'-', {
                    id:"search"
                }
                ],
                onLoadSuccess:function(data){


                }
            })

            $("a[class='row']").linkbutton({text:'下载',plain:true,iconCls:'icon-save',width:iWidth*0.03, height:20,
                onClick:function () {
                    permit = false;
                    $.post(urlSave,{cid:this.id.replace(/[a-zA-Z]/g,"")},function(result){

                    })
                }});
            $('#search').textbox({buttonText:'搜索', iconAlign:'left', width:200, height:30,prompt:"输入搜索的文档名称",
                onClickButton:function () {

                    if($('#search').textbox("getValue").replace(/(^\s*)|(\s*$)/g, "")==""){
                        $.messager.alert('确认','搜索不能为空');
                        return
                    }

                    $.get(urlSeach,{seach:$('#search').textbox("getValue")},function () {

                    })
                }
            })

            var pager = $("#shareData").datagrid("getPager");
            pager.pagination({
                total:total,
                pageList: [20,30,50,100,200,500,1000],
                pageSize:dataList.pageSize,
                pageNumber:dataList.page,
                beforePageText: '第',
                afterPageText: '页    共 ' + Math.ceil(total / dataList.pageSize) + ' 页',
                displayMsg: '当前显示 ' + (start + 1) + '-' + (start + eLength) + ' 条记录 共 ' + total + ' 条记录',
                onRefresh:function(pageNumber,pageSize){
                    $_dataGrid(pageSize,pageNumber)
                },
                onSelectPage:function (pageNo, pageSize) {
                    $_dataGrid(pageSize,pageNo)
                }
            });
        })

    }



    function $_columns() {
        var getColumns = [
            // {field: 'rowNumbers', title: '序号', align: 'center', width: 20,
            //     formatter: function(value,row,index){
            //         var op = $('#shareData').datagrid('options');
            //         return op.pageSize * (op.pageNumber - 1) + (index + 1);
            //     }
            // },
            { field: 'title', title: '文档名称', width: iWidth*0.3, align: 'left',halign: 'center'},
            { field: 'type', title: '类型', width: iWidth*0.04, align: 'center',
                formatter:function (value,row,index){
                    switch (value){
                        case 1:return "excel";
                            break;case 2:return "word";break;case 3:return "pdf";
                        break;case 4:return "zip";break;case 5:return "rar";break;
                    }
                }
            },
            { field: 'mtime', title: '共享日期', width: iWidth*0.04, align: 'center',
                formatter:function (value,row,index){
                    var myDate = new Date(value);
                    var result=myDate.getFullYear()+"年"+(myDate.getMonth()+1)+"月"+myDate.getDate()+'日'
                    return result;
                }
            },
            { field: 'editor', title: '共享人', width:  iWidth*0.03, align: 'center'},
            { field: 'format', title: '下载', width: iWidth*0.02, align: 'center',
                formatter:function (value,row,index){
                    var str = '<a href="javascript:;" class="'+"row"+'" id='+"format"+row.cid+'>下载</a>';
                    return str;
                }
            },
        ];
        return getColumns;
    }

    function $_preview(cid,title) {


        var getCid;

        var mWidth = document.documentElement.offsetWidth
        var mHeight = document.documentElement.offsetHeight

        $.get(urlInfo,{"cid":cid},function (json) {

            var obj = eval('(' + json + ')');

            var data = obj["data"]
            var info = data.info;

            console.info(data)

            if(allow){

                $('#tabView').tabs({
                    border:false,
                    scrollDuration:1,
                    onClose:function(title, index){
                        var tab = $('#tabView').tabs('tabs');
                        var len = tab.length;
                        if(len==0){
                            $('#preview').dialog('close');
                        }
                        getId.splice(index,1);
                    },
                    onSelect:function(title,index){
                        // console.info(getId)
                        getCid = getId[index]
                        // alert(getId[index])

                    }
                })

                $("#preview").dialog({
                    title: "预览",
                    width: mWidth * 0.8,
                    height: mHeight-60,
                    buttons: [{
                        text: '下载',
                        iconCls: 'icon-save',
                        width: 100,
                        handler: function () {
                            // alert(getCid)
                            $.post(urlSave,{cid:getCid},function (json) {

                            })
                        }
                    }],
                    onBeforeClose: function () {
                        //获取tabs的选项卡个数---------------------------------------------------------------------------
                        var tab = $('#tabView').tabs('tabs');
                        var len = tab.length;
                        //关闭所有选项---------------------------------------------------------------------------
                        for (var i = tab.length; i >= 0; i--) {
                            $("#tabView").tabs('close', i)
                        }
                        allow = true
                        $("a[name='opera']").linkbutton('enable');
                    },
                    onOpen: function () {
                        $("a[name='opera']").linkbutton('disable');
                    }
                })
                allow = false;
            }
            $_addView(title,info)
        })


    }

    function $_addView(title,info) {
        $('#tabView') .tabs('add', {
            title:title,
            content:info,
            closable: true,
            plain: true,
        })
    }

    function $_paging(data) {
        var pager = $("#shareData").datagrid("getPager");

        pager.pagination({
            total:data.length,
            onRefresh:function(pageNumber,pageSize){

            },
            onChangePageSize:function(){

            },
            onSelectPage:function (pageNo, pageSize) {
                var start = (pageNo - 1) * pageSize;
                var end = start + pageSize;

                var endLength = data.length%pageSize;

                if(pageNo == Math.ceil(data.length/pageSize)){
                    var eLength = endLength

                }
                else {
                    var eLength = pageSize

                }

                $("#shareData").datagrid("loadData", data.slice(start, end));
                pager.pagination('refresh', {
                    total:data.length,
                    pageNumber:pageNo
                });
            }
        });
    }

    function $_uploadView() {

        $("#uploadView").css({"display":"block"})

        $("#uploadView").dialog({
            title:"上传",
            width:500,
            height:320,
            modal:true,
            content:' <form id="fm" method="post" enctype="multipart/form-data" style=" padding: 10px; padding-bottom:5px; margin-top:20px;">' +
            '<div style=" width: 400px; margin: 0 auto;">' +
            '<div style=" margin-bottom: 20px; margin-top:10px; line-height: 25px; height:75px; ">'+
            '<span style="display:block; margin-bottom: 20px">共享人：<input id="myName"></span>'+
            '<span>共享时间：<input id="myDate"></span>'+
            '</div>'+
            '<div style="width:390px; height: 30px;  position: relative; line-height: 30px;  padding-left: 10px; border: 1px #FA8072 solid; border-radius: 5px; " id="fre">'+
            '<span style="width:310px; height: 30px;color:#ABABAB; display: inline-block; overflow: hidden; text-overflow:ellipsis; white-space: nowrap;" id="finame">请上传Excel或者Word，pdf，zip，rar</span>'+
            '<div id="browse" style="width:80px; height: 30px; background: #FA8072; border-top-right-radius: 3px;border-bottom-right-radius: 3px;float: right; font-size: 15px; text-align: center; line-height: 30px; color: #000">点击浏览</div>'+
            '<input id="fb" accept=".xls,.doc,.docx,.rar,.pdf,.zip" title="一次同时可以上传多个文件" style="width: 80px; height: 30px; position: absolute; left: 320px ;opacity: 0;filter:alpha(opacity=0); -moz-opacity:0;" name="upLoad"  multiple="multiple" required="required" type="file"/>' +
            '</div>'+
            '<div style="margin-top: 15px;">' +
            '<span id="fbName" style=" display: inline-block; width: 65%;overflow: hidden; text-overflow:ellipsis; white-space: nowrap; line-height: 25px; margin-right: 2.5% ;">文件名：</span>' +
            '<span style=" display: inline-block; width: 30%; overflow: hidden; text-overflow:ellipsis; white-space: nowrap; line-height: 25px; " id="fbSize">文件大小：</span>'+
            "<span id='up' style=' display: block; margin: 0 auto; text-align: center; font-size: 15px; padding: 3px;'></span>"+
            '</div>' +
            '</div>' +
            '</form>',
            buttons: [{
                id: "okBtn",
                text: '提交',
                iconCls: 'icon-ok',
                width: 100,
                handler: function () {
                    var iFb = document.getElementById("fb");

                    if($("#myName").textbox("getValue")==""||$("#myDate").datebox("getValue")==""||iFb.files.length==0){
                        $.messager.alert('确认','必填项不能为空')
                        return;
                    }

                    $('#fm').form('submit', {
                        url:urlSave,
                        onSubmit: function(param){

                            param.mtime = dateTime;
                            param.editor =  $("#myName").textbox("getValue")

                            var iup = document.getElementById("up");
                            iup.innerHTML = "上传中请稍等..."

                        },
                        success:function(data){
                            if(data){
                                $.messager.alert('确认','提交成功')
                                $('#uploadView').dialog('close');
                            }
                        }
                    });
                }
            }]
        })
        $("#myName").textbox({width:352,height:30,required:"required",prompt:"输入名字",})
        $("#myDate").datebox({width:340,height:30,required:"required",prompt:"输入时间",})
        $("#myDate").textbox('disable');


        var myDate = new Date();
        dateTime = myDate.getTime();
        var result=myDate.getDate()+'/'+(myDate.getMonth()+1)+"/"+myDate.getFullYear()
        $("#myDate").datebox('setValue',result)

        $_choice()
    }

    function $_choice() {
        var iFb = document.getElementById("fb");//获取上传框
        var iFiname= document.getElementById("finame");//获取显示文件个数的span
        var ifbName = document.getElementById("fbName");//获取文件名字的span
        var ifbSize = document.getElementById("fbSize");//获取文件大小的span
        var iFre = document.getElementById("fre");
        var iBrowse = document.getElementById("browse");

        var isize=0;//保存所有文件大小的数值
        var iname='';//保存文件名
        var iname2="";//提示的文件名

        iFb.onmousedown = function () {
            iBrowse.style.color = "#fff"
        }
        iFb.onmouseup = function () {
            iBrowse.style.color = "#000"
        }

        iFb.onchange = function () {

            isize = 0;
            iname="";
            iname2="";

            var fileCount = iFb.files.length;
            if(fileCount>0){
                iFre.style.borderColor = "#ccc"
                iBrowse.style.background = "#ccc"
                iFiname.style.color = "#000"
            }

            //一个文件则上传框显示文件名
            if(fileCount==1){
                ifbName.innerHTML ="文件名："+ iFb.files[0].name;
                iFiname.innerHTML = iFb.files[0].name;

                iFiname.title = iFb.files[0].name;

                if(iFb.files[0].size>=0&&iFb.files[0].size<(1024*1024)){
                    ifbSize.innerHTML = "文件大小："+((iFb.files[0].size/1024).toFixed(2))+"KB";
                }
                else if(iFb.files[0].size>=1024*1024){
                    ifbSize.innerHTML = "文件大小："+((iFb.files[0].size/(1024*1024)).toFixed(2))+"MB";
                    $.messager.alert('警告',"文件大于1M");
                }


            }
            //多个文件则显示文件个数
            else{
                iFiname.innerHTML = "已经选择"+fileCount+"个文件";
                ifbName.innerHTML ="文件名：";

                for(var i=0; i<fileCount; i++){
                    isize+=iFb.files[i].size;
                    iname+=iFb.files[i].name+"；"+"  ";
                    iname2+=iFb.files[i].name+"\n"

                }

                if(isize>=0&&isize<(1024*1024)){
                    ifbSize.innerHTML = "文件共："+((isize/1024).toFixed(2))+"KB";
                }
                else if(isize>=1024*1024){
                    ifbSize.innerHTML = "文件共："+((isize/(1024*1024)).toFixed(2))+"MB";
                    $.messager.alert('警告',"文件大于1M");
                }

                ifbName.innerHTML ="文件名："+iname;
                iFiname.title = iname2;
            }


            var arrType=[];

            for(var i=0; i<fileCount; i++){

                arrType.length = 0;

                for(var j=0; j<iFb.files[i].name.length; j++){


                    if(iFb.files[i].name[j] == "."){

                        for(var z=j+1; z<iFb.files[i].name.length; z++){

                            arrType.push(iFb.files[i].name[z])

                        }
                    }

                }

                if((arrType.join("")=="xls")||(arrType.join("")=="doc")||(arrType.join("")=="docx")||(arrType.join("")=="rar")||(arrType.join("")=="pdf")||(arrType.join("")=="zip")) {

                    $('#okBtn').linkbutton('enable');

                }
                else {

                    $('#okBtn').linkbutton('disable');

                    iFre.style.borderColor = "#FA8072"
                    iBrowse.style.background = "#FA8072"
                    iFiname.style.color = " #FA8072"
                    $.messager.alert('确认','文件不符合要求')
                    break;
                }




            }
            if(isize>1024*1024||iFb.files[0].size>1024*1024){
                $('#okBtn').linkbutton('disable');
                iFre.style.borderColor = "#FA8072"
                iBrowse.style.background = "#FA8072"
                iFiname.style.color = " #FA8072"
            }

        }

    }

})()



// function $_columns() {
//     var that = this;
//     this.getColumns = [
//         { field: 'title', title: '文档名称', width: iWidth*0.3, align: 'left',halign: 'center'},
//         { field: 'type', title: '类型', width: iWidth*0.04, align: 'center'},
//         { field: 'mtime', title: '共享日期', width: iWidth*0.04, align: 'center'},
//         { field: 'editor', title: '共享人', width:  iWidth*0.03, align: 'center'},
//         { field: 'size', title: '文档大小', width:  iWidth*0.02, align: 'center' },
//         { field: 'format', title: '下载', width: iWidth*0.02, align: 'center',formatter:function (value,row,index) {that.format(value,row,index)}},
//         {field: 'operate', title: '操作', align: 'center', width:iWidth*0.02, formatter:function (value,row,index) {that.operate(value,row,index)}}
//     ];
//     return this.getColumns;
// }
// $_columns.prototype.format = function (value,row,index){
//     var str = '<a href="javascript:;" class="'+"row"+'">下载</a>';
//     return str;
// }
// $_columns.prototype.operate = function (value, row, index) {
//     var str = '<a href="#" name="opera" class="easyui-linkbutton">删除</a>';
//     return str;
// }